package comgame.scenes;

import com.almasb.fxgl.app.scene.FXGLScene;
import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.audio.Sound;
import com.almasb.fxgl.dsl.FXGL;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

import java.util.Objects;
import java.util.HashMap;
import java.util.Map;

public class HomeScene extends FXGLScene {
    private StackPane sceneRoot;
    private javafx.scene.layout.VBox boxPane; // 物品栏容器
    private javafx.scene.control.TableView<Item> tableView; // 物品表成员变量

    
    public HomeScene() {
        System.out.println("HomeScene构造函数开始");
        
        // 在构造函数中立即隐藏player实体，避免时序问题
        if (comgame.scenes.GameScene.playerEntity != null) {
            comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(false);
        }
        initUI();

    }

    protected void initUI() {
        // 初始化根容器
        sceneRoot = new StackPane();
        sceneRoot.setPrefSize(800, 600);
        sceneRoot.setStyle("-fx-background-color: transparent;");

        // 加载背景图片
        Image backgroundImg;
        try {
            backgroundImg = new Image(Objects.requireNonNull(
                    getClass().getResourceAsStream("/assets/textures/homescene.png")));
        } catch (Exception e) {
            System.err.println("背景图片加载异常: " + e.getMessage());
            backgroundImg = null;
        }

        if (backgroundImg != null) {
            ImageView background = new ImageView(backgroundImg);
            background.setFitWidth(1000);
            background.setFitHeight(750);
            sceneRoot.getChildren().add(background);
        }

        // 主界面切换时不再stopAll，只在未播放时播放HomeMusic
        if (comgame.scenes.MusicManager.homeMusic == null)
            comgame.scenes.MusicManager.homeMusic = FXGL.getAssetLoader().loadMusic("HomeMusic.mp4");
        FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.homeMusic);
        comgame.scenes.MusicManager.isHomeMusicPlaying = true;
        System.out.println("[HomeMusic] HomeScene loopMusic已调用");

        // 初始化物品栏UI（默认隐藏）
        initBoxPane();

        // 添加返回按钮
        addBackButton();
        // 添加箱子按钮
        addBoxButton();

        getContentRoot().getChildren().add(sceneRoot);
    }

    // 初始化物品栏UI
    private void initBoxPane() {
        boxPane = new javafx.scene.layout.VBox();
        boxPane.setVisible(false);
        boxPane.setStyle("-fx-background-color: rgba(255,255,255,0.92); -fx-background-radius: 12; -fx-padding: 10; -fx-border-radius: 12; -fx-border-color: #888;");
        boxPane.setMaxWidth(350);
        boxPane.setMaxHeight(340);
        boxPane.setSpacing(8);
        boxPane.setAlignment(Pos.CENTER);

        javafx.scene.control.Label title = new javafx.scene.control.Label("物品箱");
        title.setStyle("-fx-font-size: 28px; -fx-font-weight: bold; -fx-text-fill: #333;");
        title.setPadding(new Insets(0,0,5,0));

        tableView = new javafx.scene.control.TableView<>();
        tableView.setPrefHeight(400);
        tableView.setPrefWidth(350);
        tableView.setColumnResizePolicy(javafx.scene.control.TableView.CONSTRAINED_RESIZE_POLICY);
        tableView.setStyle("-fx-font-size: 14px;");

        // 图片列
        javafx.scene.control.TableColumn<Item, String> imageCol = new javafx.scene.control.TableColumn<>("图片");
        imageCol.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("imagePath"));
        imageCol.setPrefWidth(40);
        imageCol.setCellFactory(col -> new javafx.scene.control.TableCell<Item, String>() {
            private final ImageView imageView = new ImageView();
            @Override
            protected void updateItem(String imagePath, boolean empty) {
                super.updateItem(imagePath, empty);
                if (empty || imagePath == null || imagePath.isEmpty()) {
                    setGraphic(null);
                } else {
                    try {
                        Image img = new Image(getClass().getResourceAsStream(imagePath), 30, 30, true, true);
                        imageView.setImage(img);
                        setGraphic(imageView);
                    } catch (Exception e) {
                        setGraphic(null);
                    }
                }
            }
        });

        // 名称列
        javafx.scene.control.TableColumn<Item, String> nameCol = new javafx.scene.control.TableColumn<>("物品名称");
        nameCol.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("name"));
        nameCol.setPrefWidth(120);
        nameCol.setStyle("-fx-font-size: 14px;");
        // 空栏位不显示名称
        nameCol.setCellFactory(col -> new javafx.scene.control.TableCell<Item, String>() {
            @Override
            protected void updateItem(String name, boolean empty) {
                super.updateItem(name, empty);
                if (empty || name == null || name.isEmpty()) {
                    setText("");
                } else {
                    setText(name);
                }
            }
        });

        // 数量列
        javafx.scene.control.TableColumn<Item, Integer> countCol = new javafx.scene.control.TableColumn<>("数量");
        countCol.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("count"));
        countCol.setPrefWidth(60);
        countCol.setStyle("-fx-font-size: 14px;");
        // 空栏位不显示数量
        countCol.setCellFactory(col -> new javafx.scene.control.TableCell<Item, Integer>() {
            @Override
            protected void updateItem(Integer count, boolean empty) {
                super.updateItem(count, empty);
                if (empty || count == null || count == 0) {
                    setText("");
                } else {
                    setText(String.valueOf(count));
                }
            }
        });

        // 操作列（装备类物品显示“装备”按钮或“已装备”标签）
        javafx.scene.control.TableColumn<Item, Void> actionCol = new javafx.scene.control.TableColumn<>("操作");
        actionCol.setPrefWidth(80);
        actionCol.setCellFactory(col -> new javafx.scene.control.TableCell<Item, Void>() {
            private final Button equipBtn = new Button("装备");
            private final Button unequipBtn = new Button("卸下");
            {
                equipBtn.setOnAction(e -> {
                    Item item = tableView.getItems().get(getIndex());
                    String name = item.getName();
                    String type = getEquipType(name);
                    // 判断是否为装备类且未装备且同类未装备
                    boolean sameTypeEquipped = GameScene.player.isEquipped(type);
                    if (isEquipable(name) && !item.isEquipped() && !sameTypeEquipped) {
                        GameScene.player.equipByName(name);
                        item.setEquipped(true);
                        System.out.println("装备: " + name + " 类型: " + type);
                        GameScene.player.showEquipmentStatus();
                        tableView.refresh();
                        // 通知GameScene更新属性面板
                        notifyGameSceneUpdate();
                        comgame.scenes.DataSaveManager.saveAll();
                    } else if (item.isEquipped()) {
                        FXGL.showMessage("该装备已装备");
                    } else if (sameTypeEquipped) {
                        FXGL.showMessage("同类装备只能装备一个");
                    }
                });
                
                unequipBtn.setOnAction(e -> {
                    Item item = tableView.getItems().get(getIndex());
                    String name = item.getName();
                    String type = getEquipType(name);
                    
                    if (isEquipable(name) && item.isEquipped()) {
                        GameScene.player.unequipByType(type);
                        item.setEquipped(false);
                        System.out.println("卸下装备: " + name + " 类型: " + type);
                        GameScene.player.showEquipmentStatus();
                        tableView.refresh();
                        // 通知GameScene更新属性面板
                        notifyGameSceneUpdate();
                        comgame.scenes.DataSaveManager.saveAll();
                    }
                });
                
                // 设置按钮样式
                equipBtn.setStyle("-fx-background-color: #4CAF50; -fx-text-fill: white; -fx-font-weight: bold;");
                unequipBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white; -fx-font-weight: bold;");
            }
            @Override
            protected void updateItem(Void v, boolean empty) {
                super.updateItem(v, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    Item item = tableView.getItems().get(getIndex());
                    String type = getEquipType(item.getName());
                    boolean isEquipped = GameScene.player.isEquipped(type) && item.getName().equals(GameScene.player.getEquippedItemName(type));
                    if (isEquipable(item.getName())) {
                        if (isEquipped) {
                            setGraphic(unequipBtn);
                            item.setEquipped(true);
                        } else if (item.getCount() > 0 && !isEquipped) {
                            setGraphic(equipBtn);
                            item.setEquipped(false);
                        } else {
                            setGraphic(null);
                            item.setEquipped(false);
                        }
                    } else {
                        setGraphic(null);
                        item.setEquipped(false);
                    }
                }
            }
        });
        tableView.getColumns().add(actionCol);

        // 价格列
        javafx.scene.control.TableColumn<Item, Integer> priceCol = new javafx.scene.control.TableColumn<>("价格");
        priceCol.setCellValueFactory(new javafx.scene.control.cell.PropertyValueFactory<>("price"));
        priceCol.setPrefWidth(60);
        priceCol.setStyle("-fx-font-size: 14px;");
        // 空栏位不显示价格
        priceCol.setCellFactory(col -> new javafx.scene.control.TableCell<Item, Integer>() {
            @Override
            protected void updateItem(Integer price, boolean empty) {
                super.updateItem(price, empty);
                if (empty || price == null || price == 0) {
                    setText("");
                } else {
                    setText(String.valueOf(price));
                }
            }
        });

        tableView.getColumns().addAll(imageCol, nameCol, countCol, priceCol);

        final int MAX_ITEM_SLOTS = 20;
        // 使用ItemManager获取数据
        java.util.List<Item> items = new java.util.ArrayList<>();
        Map<String, Integer> itemData = ItemManager.getInstance().getAllItems();
        // 物品图片映射（农作物+装备+种子+钓鱼特殊物品）
        Map<String, String> itemImages = new HashMap<>();
        // 农作物
        itemImages.put("小麦", "/assets/textures/Fruit_Wheat.png");
        itemImages.put("番茄", "/assets/textures/Fruit_Tomato.png");
        itemImages.put("土豆", "/assets/textures/Fruit_Potato.png");
        itemImages.put("星果", "/assets/textures/Fruit_Starfruit.png");
        itemImages.put("胡萝卜", "/assets/textures/Fruit_Carrot.png");
        // 特殊农作物
        itemImages.put("南瓜", "/assets/textures/Fruit_Pumpkin.png");
        itemImages.put("霜瓜", "/assets/textures/Fruit_Powdermelon.png");
        itemImages.put("幽灵辣椒", "/assets/textures/Fruit_GhostPaper.png");
        itemImages.put("水龙果", "/assets/textures/Fruit_WaterDragon.png");
        itemImages.put("齐瓜", "/assets/textures/Fruit_Qi_Fruit.png");
        // 种子
        itemImages.put("小麦种子", "/assets/textures/Seed_Wheat.png");
        itemImages.put("番茄种子", "/assets/textures/Seed_Tomato.png");
        itemImages.put("土豆种子", "/assets/textures/Seed_Potato.png");
        itemImages.put("星果种子", "/assets/textures/Seed_Starfruit.png");
        itemImages.put("胡萝卜种子", "/assets/textures/Seed_Carrot.png");
        // 特殊种子
        itemImages.put("南瓜种子", "/assets/textures/Seed_Pumpkin.png");
        itemImages.put("霜瓜种子", "/assets/textures/Seed_Powdermelon.png");
        itemImages.put("幽灵辣椒种子", "/assets/textures/Seed_GhostPaper.png");
        itemImages.put("水龙果种子", "/assets/textures/Seed_WaterDragon.png");
        itemImages.put("齐瓜种子", "/assets/textures/Seed_Qi_Bean.png");
        // 装备 - 剑
        itemImages.put("铁剑", "/assets/textures/Sword_Iron.png");
        itemImages.put("普通剑", "/assets/textures/Sword_Normal.png");
        itemImages.put("金剑", "/assets/textures/Sword_Golden.png");
        itemImages.put("钻石剑", "/assets/textures/Sword_Diamond.png");
        // 装备 - 头盔
        itemImages.put("铁头盔", "/assets/textures/Helmet_iron.png");
        itemImages.put("普通头盔", "/assets/textures/Helmet_normal.png");
        itemImages.put("金头盔", "/assets/textures/Helmet_golden.png");
        itemImages.put("钻石头盔", "/assets/textures/Helmet_diamond.png");
        // 装备 - 胸甲
        itemImages.put("铁胸甲", "/assets/textures/Chestplate_iron.png");
        itemImages.put("普通胸甲", "/assets/textures/Chestplate_normal.png");
        itemImages.put("金胸甲", "/assets/textures/Chestplate_golden.png");
        itemImages.put("钻石胸甲", "/assets/textures/Chestplate_diamond.png");
        // 装备 - 护腿
        itemImages.put("铁护腿", "/assets/textures/Legging_iron.png");
        itemImages.put("普通护腿", "/assets/textures/Legging_normal.png");
        itemImages.put("金护腿", "/assets/textures/Legging_golden.png");
        itemImages.put("钻石护腿", "/assets/textures/Legging_diamond.png");
        // 装备 - 靴子
        itemImages.put("铁靴子", "/assets/textures/Boot_iron.png");
        itemImages.put("普通靴子", "/assets/textures/Boot_normal.png");
        itemImages.put("金靴子", "/assets/textures/Boot_golden.png");
        itemImages.put("钻石靴子", "/assets/textures/Boot_diamond.png");
        // 钓鱼特殊物品
        itemImages.put("钓上来的头骨", "/assets/textures/Fishing_DeadPeople.png");
        itemImages.put("稀有破烂", "/assets/textures/Fishing_RareStuff.png");
        itemImages.put("石头", "/assets/textures/Fishing_Rock.png");
        itemImages.put("臭靴子", "/assets/textures/Fishing_Stinky_Boost.png");
        itemImages.put("木头", "/assets/textures/Fishing_Wood.png");
        // 第二阶段钓鱼物品
        itemImages.put("贝壳", "/assets/textures/Fishing_Clam.png");
        itemImages.put("珊瑚", "/assets/textures/Fishing_Coral.png");
        itemImages.put("死鱼", "/assets/textures/Fishing_DeadFish.png");
        itemImages.put("北极甜虾", "/assets/textures/fish_ArcticShrimp.png");
        
        // 新增材料类
        itemImages.put("史莱姆凝胶", "/assets/textures/Item_Slime.png");
        itemImages.put("昆虫肉", "/assets/textures/Item_Bug_Meat.png");
        // 新增装备类
        itemImages.put("幽灵剑", "/assets/textures/Sword_Ghost.png");
        itemImages.put("无头骑士剑", "/assets/textures/Sowrd_Pumpkin.png");
        itemImages.put("泰拉棱镜", "/assets/textures/Sword_Terraprisma.png");
        itemImages.put("喜庆之翼", "/assets/textures/Helmet_Festive_Wings.png");
        itemImages.put("幽灵靴子", "/assets/textures/Boots_Ghost.png");
        itemImages.put("幽灵护腿", "/assets/textures/Leggings_Ghost.png");
        itemImages.put("幽灵胸甲", "/assets/textures/Chestplate_Ghost.png");
        itemImages.put("幽灵头盔", "/assets/textures/Helmet_Ghost.png");
        itemImages.put("空间之主靴子", "/assets/textures/Boots_SpaceKing.png");
        itemImages.put("空间之主护腿", "/assets/textures/Legging_SpaceKing.png");
        itemImages.put("空间之主胸甲", "/assets/textures/Chestplate_SpaceKing.png");
        itemImages.put("空间之主头盔", "/assets/textures/Helmet_SpaceKing.png");
        itemImages.put("幼苗", "/assets/textures/Plantera_Seed.png");
        
        // 显示农作物、种子和钓鱼物品
        String[] showItems = {"小麦", "番茄", "土豆", "星果", "胡萝卜", "南瓜", "霜瓜", "幽灵辣椒", "水龙果", "齐瓜", "小麦种子", "番茄种子", "土豆种子", "星果种子", "胡萝卜种子", "南瓜种子", "霜瓜种子", "幽灵辣椒种子", "水龙果种子", "齐瓜种子", "钓上来的头骨", "稀有破烂", "石头", "臭靴子", "木头", "贝壳", "珊瑚", "死鱼", "北极甜虾", "史莱姆凝胶", "昆虫肉", "幼苗"};
        for (String name : showItems) {
            Integer count = itemData.get(name);
            if (count != null && count > 0) {
                String imagePath = itemImages.getOrDefault(name, "");
                items.add(new Item(name, count, imagePath));
            }
        }
        // 统计每种装备的数量
        String[] equipItems = {
            // 剑
            "铁剑", "普通剑", "金剑", "钻石剑", "幽灵剑", "无头骑士剑", "泰拉棱镜",
            // 头盔
            "铁头盔", "普通头盔", "金头盔", "钻石头盔", "幽灵头盔", "空间之主头盔",
            // 胸甲
            "铁胸甲", "普通胸甲", "金胸甲", "钻石胸甲", "幽灵胸甲","喜庆之翼", "空间之主胸甲",
            // 护腿
            "铁护腿", "普通护腿", "金护腿", "钻石护腿", "幽灵护腿", "空间之主护腿",
            // 靴子
            "铁靴子", "普通靴子", "金靴子", "钻石靴子", "幽灵靴子", "空间之主靴子"
        };
        Map<String, Integer> equipCountMap = new HashMap<>();
        for (String name : equipItems) {
            Integer count = itemData.get(name);
            String imagePath = itemImages.getOrDefault(name, "");
            if (count != null && count > 0) {
                equipCountMap.put(name, count);
            }
        }
        // 装备类物品每个都单独一行，数量合并
        for (String name : equipItems) {
            if (equipCountMap.containsKey(name)) {
                String imagePath = itemImages.getOrDefault(name, "");
                items.add(new Item(name, equipCountMap.get(name), imagePath));
            }
        }
        // 补充空栏位（总共显示10个栏位）
        int minSlots = 10;
        while (items.size() < minSlots) {
            items.add(new Item("", 0, ""));
        }
        tableView.getItems().addAll(items);

        // 刷新装备状态：全部设为未装备，再根据装备管理器设为已装备
        for (Item item : items) {
            if (isEquipable(item.getName())) {
                item.setEquipped(false);
                String type = getEquipType(item.getName());
                // 使用物品名称而不是ID来匹配装备状态
                if (GameScene.player.isEquipped(type)) {
                    String equippedItemName = GameScene.player.getEquippedItemName(type);
                    if (equippedItemName != null && equippedItemName.equals(item.getName())) {
                        item.setEquipped(true);
                    }
                }
            }
        }
        
        // 确保玩家实体存在并且有AttributeComponent


        boxPane.getChildren().addAll(title, tableView);

        // 放在界面中间
        StackPane.setAlignment(boxPane, Pos.CENTER);
        StackPane.setMargin(boxPane, new Insets(0,0,0,0));
        boxPane.setMaxWidth(400);
        boxPane.setMaxHeight(450);
        boxPane.setPrefWidth(400);
        boxPane.setPrefHeight(450);
        sceneRoot.getChildren().add(boxPane);
    }

    // 添加返回按钮的方法
    private void addBackButton() {
        // 加载按钮音效（与GameScene保持一致）
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("drop.wav");

        // 创建返回按钮（使用与其他按钮一致的风格）
        Button backBtn = createSingleImageButton(
                "/assets/textures/back button4.png",  // 建议准备一个返回按钮图片
                "返回",
                0.1  // 缩放比例，可根据图片大小调整
        );

        // 设置按钮位置（左上角）
        StackPane.setAlignment(backBtn, Pos.TOP_LEFT);
        StackPane.setMargin(backBtn, new Insets(20, 0, 0, 20));  // 左上角边距

        // 绑定点击事件（返回GameScene）
        backBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);  // 播放点击音效
            System.out.println("返回主场景");
            comgame.scenes.DataSaveManager.saveAll();
            comgame.scenes.DataSaveManager.loadAll();
            FXGL.getGameScene().clearUINodes();
            GameScene gameScene = new GameScene();
            FXGL.getGameScene().addUINode(gameScene.getSceneRoot());
            // 确保player实体可见或重新创建
            if (comgame.scenes.GameScene.playerEntity != null && comgame.scenes.GameScene.playerEntity.isActive()) {
                comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(true);
            } else {
                // 如果玩家实体不存在或不活跃，重新创建
                comgame.scenes.GameScene.recreatePlayerEntity();
            }
        });

        // 将按钮添加到场景
        sceneRoot.getChildren().add(backBtn);
    }

    // 添加箱子按钮的方法
    private void addBoxButton() {
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("drop.wav");

        Button boxBtn = createSingleImageButton(
                "/assets/textures/Box.png",
                "箱子",
                1 // 缩放比例，可根据图片大小调整
        );

        // 设置按钮位置（场景中央）
        StackPane.setAlignment(boxBtn, Pos.CENTER);
        StackPane.setMargin(boxBtn, new Insets(500, -200, 0, 0)); // 向下并向右移动100像素

        // 绑定点击事件，切换物品栏显示/隐藏
        boxBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            boxPane.setVisible(!boxPane.isVisible());
        });

        sceneRoot.getChildren().add(boxBtn);
    }

    // 物品数据类，增加图片路径和价格
    public static class Item {
        private final javafx.beans.property.SimpleStringProperty name;
        private final javafx.beans.property.SimpleIntegerProperty count;
        private final javafx.beans.property.SimpleStringProperty imagePath;
        private final javafx.beans.property.SimpleIntegerProperty price;
        private boolean equipped = false;
        private final String id; // 唯一ID

        public Item(String name, int count, String imagePath, String id) {
            this.name = new javafx.beans.property.SimpleStringProperty(name);
            this.count = new javafx.beans.property.SimpleIntegerProperty(count);
            this.imagePath = new javafx.beans.property.SimpleStringProperty(imagePath);
            this.price = new javafx.beans.property.SimpleIntegerProperty(0);
            this.id = id;
        }
        // 保留原有构造方法，非装备类用UUID
        public Item(String name, int count, String imagePath) {
            this(name, count, imagePath, java.util.UUID.randomUUID().toString());
        }
        public String getName() { return name.get(); }
        public void setName(String n) { name.set(n); }
        public int getCount() { return count.get(); }
        public void setCount(int c) { count.set(c); }
        public String getImagePath() { return imagePath.get(); }
        public void setImagePath(String p) { imagePath.set(p); }
        public int getPrice() { return price.get(); }
        public void setPrice(int p) { price.set(p); }
        public boolean isEquipped() { return equipped; }
        public void setEquipped(boolean equipped) { this.equipped = equipped; }
        public String getId() { return id; }
    }

    // 复用GameScene中的按钮创建方法（保持风格一致）
    private Button createSingleImageButton(String imagePath, String text, double scale) {
        // 加载图片
        Image buttonImage = new Image(Objects.requireNonNull(getClass().getResourceAsStream(imagePath)));

        // 创建按钮（不设置文本，只显示图片）
        Button button = new Button();
        ImageView imageView = new ImageView(buttonImage);

        // 应用缩放
        imageView.setFitWidth(buttonImage.getWidth() * scale);
        imageView.setFitHeight(buttonImage.getHeight() * scale);
        button.setGraphic(imageView);

        // 设置按钮尺寸
        button.setPrefSize(imageView.getFitWidth(), imageView.getFitHeight());

        // 移除默认样式
        button.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");

        // 创建阴影效果（悬停时使用）
        DropShadow shadow = new DropShadow();
        shadow.setColor(Color.WHITE);
        shadow.setRadius(10);

        // 设置按钮状态变化事件
        button.setOnMouseEntered(e -> {
            button.setEffect(shadow);        // 添加阴影
            button.setOpacity(0.9);          // 轻微透明
        });

        button.setOnMouseExited(e -> {
            button.setEffect(null);          // 移除阴影
            button.setOpacity(1.0);          // 恢复不透明
        });

        button.setOnMousePressed(e -> {
            button.setOpacity(0.8);          // 点击时更透明
            button.setScaleX(0.98);          // 轻微缩小
            button.setScaleY(0.98);
        });

        button.setOnMouseReleased(e -> {
            button.setOpacity(0.9);          // 恢复悬停状态
            button.setScaleX(1.0);           // 恢复大小
            button.setScaleY(1.0);
        });

        return button;
    }

    // 判断物品是否为可装备类型
    private static boolean isEquipable(String name) {
        // 臭鞋子不是可装备的物品
        if (name.equals("臭靴子")) {
            return false;
        }
        // 泰拉棱镜也属于剑类装备
        if (name.equals("泰拉棱镜")) {
            return true;
        }
        // 喜庆之翼属于胸甲
        if (name.equals("喜庆之翼")) {
            return true;
        }
        return name.contains("剑") || name.contains("头盔") || name.contains("胸甲") || name.contains("护腿") || name.contains("靴子");
    }
    // 获取装备类型（用于同类装备互斥）
    private static String getEquipType(String name) {
        if (name.equals("泰拉棱镜")) return "sword";
        if (name.equals("喜庆之翼")) return "chestplate";
        if (name.contains("头盔")) return "helmet";
        if (name.contains("胸甲")) return "chestplate";
        if (name.contains("护腿")) return "legging";
        if (name.contains("靴子")) return "boot";
        if (name.contains("剑")) return "sword";
        return name;
    }
    

    
    // 显示当前玩家属性
    private static void showPlayerAttributes() {
        if (GameScene.player != null) {
            System.out.println("=== 当前玩家属性 ===");
            System.out.println("攻击: " + GameScene.player.getAttack());
            System.out.println("防御: " + GameScene.player.getDefense());
            System.out.println("速度: " + GameScene.player.getSpeed());
            System.out.println("暴击率: " + GameScene.player.getCritRate());
            System.out.println("==================");
        } else {
            System.out.println("警告: 玩家不存在，无法显示属性");
        }
    }

    // 通知GameScene更新属性面板
    private static void notifyGameSceneUpdate() {
        // 使用Platform.runLater确保在JavaFX线程中执行
        javafx.application.Platform.runLater(() -> {
            // 强制更新GameScene的属性面板
            GameScene.forceUpdatePlayerInfoPanel();
            // 延迟一小段时间后再次更新，确保数据同步
            javafx.animation.Timeline delayUpdate = new javafx.animation.Timeline(
                new javafx.animation.KeyFrame(javafx.util.Duration.seconds(0.05), e -> {
                    GameScene.forceUpdatePlayerInfoPanel();
                })
            );
            delayUpdate.play();
        });
    }

    public StackPane getSceneRoot() {
        return sceneRoot;
    }
}
